package com.zhenyi.youqu.api;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.cenjiawen.common.IndexController;
import com.jfinal.kit.JsonKit;
import com.utils.PathUtils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.file.FileWriter;

/**
 * 支付宝支付
 * 
 * @author cen
 *
 */
public class AliBillController extends IndexController {

	String ALIPAY_PUBLIC_KEY = new FileReader(
			PathUtils.getFile("cert", "alipay_public_key_sha256_2019041063847202.txt")).readString();
	private final String CHARSET = "utf8";

	public void billPush() {
		HttpServletRequest request = getRequest();
		// 获取支付宝POST过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		String path = PathUtils.getFile("data", "youqu", "aliPush", DateUtil.today() + ".txt");
		FileWriter fileWriter = new FileWriter(path);
		Map<?, ?> requestParams = request.getParameterMap();
		fileWriter.append(DateUtil.now() + "---------\n");
		fileWriter.append(JsonKit.toJson(requestParams) + "\n");
		for (Iterator<?> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		// 切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
		// boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String
		// publicKey, String charset, String sign_type)
		try {
			boolean flag = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, "RSA2");
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		renderSuccess();
	}
}
